#!/usr/bin/perl

#
# linearly interpolates the Y datapoints from a XY file to match the X points in another file
#

if (($ARGV[0] eq '') || ($ARGV[0] eq '-h')){
	print "tinterpolate <x values file> <xy values file>\n";
	exit;
}

$file1 = $ARGV[0];
$file2 = $ARGV[1];
if (! -e $file1){
	print "File \"$file1\" does not exist.\n";
	exit;
}elsif(! -e $file2){
	print "File \"$file2\" does not exist.\n";
	exit;
}

# extract the columns
@col0_x = split(/[\r\n]/,`tread -w -col 0 $file1`);
@col1_x = split(/[\r\n]/,`tread -w -col 0 $file2`);
@col1_y = split(/[\r\n]/,`tread -w -col 1 $file2`);

# remove rows with nonnumeric x-values
$i=0;
while($i<=$#col0_x){
	if (isnum($col0_x[$i])==0){
		splice(@col0_x, $i, 1);
	}
	$i++;
}

$i=0;
while($i<=$#col1_x){
	if (isnum($col1_x[$i])==0){
		splice(@col1_x, $i, 1);
		splice(@col1_y, $i, 1);
	}
	$i++;
}

# for each x,y pair in column 0, find the flanking x1, x2 and y1, y2 points
for($i=0; $i<$#col0_x; $i++)
{
	for($j=0; $j<$#col1_x; $j++)
	{
		# if we have the flanking points, interpolate the y value
		if (($col0_x[$i] >= $col1_x[$j]) && ($col0_x[$i] < $col1_x[$j+1]))
		{
			# simple linear interpolation
			$y = $col1_y[$j] + (($col0_x[$i]-$col1_x[$j])*(($col1_y[$j+1]-$col1_y[$j])/($col1_x[$j+1]-$col1_x[$j])));
			
			print $col0_x[$i]."\t$y\n";
			last;
		}
	}
}

sub isnum
{
	$val = $_[0];
	if ($val =~ /^[\+-]?[0-9]*\.*[0-9]*E?[\+-]?[0-9]*$/ && $val !~ /^[\. ]*$/ ) {
		return 1;
	}
	return 0;
}